import React from "react"
import PropTypes from "prop-types"
import { observer, inject } from "mobx-react"
import themes from "../themes"
import ApiModel from "../../../api/apiModel/apiModel"
import ProvideImg from "../../../components/provideImg/provideImg"
import EndPop from "../../../components/pops/endPop"
import Example from "../../example/example"

import "./uploadMsg.scss"

@inject("UserStore")
@observer
class UploadMsg extends React.Component {
  static contextTypes = {
    router: PropTypes.object.isRequired,
  }
  constructor(props) {
    super(props)
    this.state = {
      confirmPopFlag: false,
      textarea: "",
      imgFlagArray: [1, 1, 1, 1], // 1 成功 2 正在 3 失败
      imagesArrays: ["", "", "", ""],
      textareas: "",
      provideImgFlag: false,
      newArray: [],
      exampleFlag: false,
    }
  }
  componentWillMount() {}
  componentDidUpdate() {}
  componentDidMount() {}
  // 输入框失去焦点
  outFocus = () => {
    window.scrollTo(0, document.documentElement.clientHeight)
  }
  setValue = (e, key) => {
    this.setState({
      [key]: e.target.value,
    })
  }
  setImagesArray = () => {
    let result = this.state.imagesArrays.filter(function (s) {
      return s && s.trim()
    })
    return result
  }
  componentWillUnmount() {}
  setImgUrl = (e, index) => {
    let file = e.currentTarget.files[0]
    if (file && file !== undefined) {
      let params = new FormData()
      params.append("file", file)
      let imgFlagArray = this.state.imgFlagArray
      imgFlagArray[index] = 2
      this.setState(
        {
          imgFlagArray,
        },
        () => {
          ApiModel.uploadImg(params).then((res) => {
            if (res.code === 0) {
              let imgFlagArray = this.state.imgFlagArray
              imgFlagArray[index] = 1
              this.setState({
                imgFlagArray,
              })
              let aa = this.state.imagesArrays
              aa[index] = res.data.url
              this.setState({
                imagesArrays: aa,
              })
              // this.props.UserStore.setImgsArray(res.data.url, index)
            } else {
              let imgFlagArray = this.state.imgFlagArray
              imgFlagArray[index] = 3
              this.setState({
                imgFlagArray,
              })
            }
          })
        }
      )
    }
  }

  setErrorMsg = (errMsg) => {
    this.props.UserStore.setErrorMsg(true, errMsg)
    this.timer = setTimeout(() => {
      this.props.UserStore.setErrorMsg(false, "")
    }, 3000)
  }

  showOrHideLoading = (flag, msg) => {
    this.props.UserStore.setPostOrGetData(flag, msg)
  }

  delimg = (index) => {
    let { imagesArrays } = this.state
    imagesArrays[index] = ""
    this.setState({
      imagesArrays,
    })
  }

  checkBtnType = () => {
    let { imagesArrays, textareas } = this.state
    if (imagesArrays.includes("")) {
      return false
    } else if (textareas == "") {
      return false
    } else {
      return true
    }
  }
  showErrorPop = () => {
    let { imagesArrays, textareas } = this.state
    for (let i = 0; i < imagesArrays.length; i++) {
      let errMsg = "请上传正面图"
      if (imagesArrays[i] === "") {
        if (i === 0) {
          errMsg = "请上传正面图"
        } else if (i === 1) {
          errMsg = "请上传侧面图"
        } else if (i === 2) {
          errMsg = "请上传背面图"
        } else {
          errMsg = "请上传参考图"
        }
        this.setErrorMsg(errMsg)
        return
      }
    }
    if (textareas == "") this.setErrorMsg("请填写详细描述")
  }
  postUploadMsg = () => {
    let that = this
    let { theme, themeChild, repeatUploadFlag } = this.props.UserStore

    let { imagesArrays, textareas } = this.state
    let params = {
      description: textareas,
      imgs: imagesArrays,
      theme: theme,
      theme_child: themeChild,
    }

    if (repeatUploadFlag) {
      params["reset"] = true
    } else {
      params["reset"] = false
    }
    this.setState({
      confirmPopFlag: false,
    })
    this.showOrHideLoading(true, "loading")
    ApiModel.postUserEntry(params).then((res) => {
      if (res.code === 0) {
        setTimeout(() => {
          this.showOrHideLoading(false, "")
          this.props.UserStore.changeValus("repeatUploadFlag", false)
          this.props.UserStore.changeUserState("uploadSuccess")
        }, 500)
      } else {
        setTimeout(() => {
          this.showOrHideLoading(false, "")
          that.setErrorMsg("作品上传失败,<br/>请稍后重试")
        }, 500)
      }
    })
  }
  changePage = (page) => {
    console.log(this.props)

    // this.props.history.push({ pathname: page })
  }

  showProvideImg = (index) => {
    let { imagesArrays } = this.state

    let newArray = []
    if (index == 0) {
      newArray = imagesArrays
    } else if (index == 1) {
      newArray.push(imagesArrays[1])
      newArray.push(imagesArrays[2])
      newArray.push(imagesArrays[3])
      newArray.push(imagesArrays[0])
    } else if (index == 2) {
      newArray.push(imagesArrays[2])
      newArray.push(imagesArrays[3])
      newArray.push(imagesArrays[0])
      newArray.push(imagesArrays[1])
    } else {
      newArray.push(imagesArrays[3])
      newArray.push(imagesArrays[0])
      newArray.push(imagesArrays[1])
      newArray.push(imagesArrays[2])
    }
    let result = newArray.filter(function (s) {
      return s && s.trim()
    })
    this.setState({
      provideImgFlag: true,
      newArray: result,
    })
    // let result = this.state.imagesArrays.filter(function (s) {
    //   return s && s.trim()
    // })
    // return result
  }

  changeExampleFlag = () => {
    this.setState({
      exampleFlag: !this.state.exampleFlag,
    })
  }

  render() {
    const {
      imgsArray,
      description,
      mode,
      themeIndex,
      themeChildIndex,
      repeatUploadFlag,
    } = this.props.UserStore
    let { imgFlagArray, imagesArrays, textareas } = this.state
    let confirmPop = (
      <div className="confirm-pop-area">
        <img
          className="pop-icon"
          src={require("../../../static/upload/img_tankuang_bubu@3x.png")}
          alt=""
        />
        <div className="pop-main">
          {repeatUploadFlag ? (
            <div className="pop-desc" style={{ textAlign: "center" }}>
              确定上传作品吗？
            </div>
          ) : (
            <div className="pop-desc">作品一旦上传将无法修改，确定上传吗？</div>
          )}
          <div className="pop-btns">
            <div
              className="btn-item cancel"
              onClick={() => {
                this.setState({
                  confirmPopFlag: false,
                })
              }}
            >
              取消
            </div>
            <div
              className="btn-item confirm"
              onClick={() => {
                this.postUploadMsg()
              }}
            >
              确定
            </div>
          </div>
        </div>
      </div>
    )
    return (
      <div className="upload-msg-container">
        <EndPop />
        {this.state.exampleFlag && (
          <Example hidePop={() => this.changeExampleFlag()} />
        )}
        {this.state.provideImgFlag && (
          <ProvideImg
            imgsArrayShow={this.state.newArray}
            hideProvide={() =>
              this.setState({
                provideImgFlag: false,
              })
            }
          />
        )}
        <div className="top-area"></div>
        {mode === 1 && (
          <div className="upload-msg-title xuexiao">
            <div className="upload-msg-text">上传作品</div>
          </div>
        )}
        {mode === 2 && (
          <div className="upload-msg-title jiating">
            <div className="upload-msg-text">上传作品</div>
          </div>
        )}
        <div className="upload-msg-area">
          <div
            className="upload-title"
            onClick={() => {
              this.props.UserStore.changeUserState("theme")
            }}
          >
            <img
              className="title-left"
              src={require("../../../static/upload/icon_shuzi_1@3x.png")}
              alt=""
            />
            <div className="title-mid">选择主题</div>
            <div className="title-right change-theme">
              <img
                className="change-theme-icon"
                src={require("../../../static/upload/icon_qiehuan@3x.png")}
                alt=""
              />
              <div>切换</div>
            </div>
          </div>
          {/* 主题部分 */}
          <div className="theme-area">
            <img
              className="theme-mian"
              src={themes[themeIndex].childrens[themeChildIndex].url}
              alt=""
            />
            <div className="theme-desc">
              {themes[themeIndex].name} -{" "}
              {themes[themeIndex].childrens[themeChildIndex].name}
            </div>
          </div>

          <div className="upload-title">
            <img
              className="title-left"
              src={require("../../../static/upload/icon_shuzi_2@3x.png")}
              alt=""
            />
            <div className="title-mid">作品展示</div>
            <div
              className="title-right"
              onClick={() => this.changeExampleFlag()}
              // onClick={() => this.context.router.history.push('/example')}
            >
              查看示范
            </div>
          </div>
          {/* 上传作品部分 */}
          <div className="upload-area">
            {imagesArrays.map((imgItem, imgIndex) => {
              return (
                <div className="upload-item" key={imgIndex}>
                  <div>
                    {imgItem ? (
                      <div className="uploaded-img-area">
                        <img
                          // onClick={() => {
                          //   this.showProvideImg(imgIndex)
                          // }}
                          className="uploaded-img"
                          src={imgItem}
                          alt=""
                        />
                        <img
                          onClick={() => {
                            this.delimg(imgIndex)
                          }}
                          className="del-icon"
                          src={require("../../../static/upload/btn_shangchuan_shanchu@3x.png")}
                          alt=""
                        />
                      </div>
                    ) : (
                      <div>
                        {imgFlagArray[imgIndex] === 3 && (
                          <div className="item-icon error">
                            <div className="icon-error-desc">上传失败</div>
                          </div>
                        )}
                        {imgFlagArray[imgIndex] === 2 && (
                          <div className="item-icon error">
                            <div className="icon-error-desc">上传中</div>
                          </div>
                        )}
                        {imgFlagArray[imgIndex] === 1 && (
                          <div className="item-icon"></div>
                        )}
                      </div>
                    )}

                    {imgFlagArray[imgIndex] !== 2 &&
                      imgFlagArray[imgIndex] !== 3 && (
                        <div className="icon-desc">
                          {imagesArrays[imgIndex] == "" && (
                            <div>
                              {imgIndex === 0 && "作品正面"}
                              {imgIndex === 1 && "作品侧面"}
                              {imgIndex === 2 && "作品背面"}
                              {imgIndex === 3 && "参考建筑"}
                            </div>
                          )}
                        </div>
                      )}

                    {!imgItem && imgFlagArray[imgIndex] !== 2 && (
                      <input
                        className="up-input"
                        onChange={(e) => this.setImgUrl(e, imgIndex)}
                        type="file"
                        accept="image/*"
                      />
                    )}
                  </div>
                </div>
              )
            })}
          </div>
          <div className="upload-title">
            <img
              className="title-left"
              src={require("../../../static/upload/icon_shuzi_3@3x.png")}
              alt=""
            />
            <div className="title-mid">作品介绍</div>
            <div className="title-right text-num">{textareas.length} 字</div>
          </div>
          {/* 简介部分 */}
          <div className="upload-desc">
            <textarea
              className="upload-desc-testarea"
              onBlur={this.outFocus}
              onChange={
                (e) =>
                  this.setState({
                    textareas: e.target.value,
                  })
                // this.props.UserStore.changeValus('description', e.target.value)
              }
              value={textareas}
              // maxLength={50}
              placeholder="请准确描述作品整体的长宽高，并介绍参考的闵行文旅特色建筑，展示作品的搭建灵感"
            ></textarea>
          </div>
          {/* 上传按钮 */}
          {this.checkBtnType() ? (
            <div
              className="upload-btn"
              onClick={() => {
                this.setState({
                  confirmPopFlag: true,
                })
              }}
            >
              提交作品
            </div>
          ) : (
            <div
              className="upload-btn no-use"
              onClick={() => {
                this.showErrorPop()
              }}
            >
              提交作品
            </div>
          )}
        </div>
        {this.state.confirmPopFlag && confirmPop}
      </div>
    )
  }
}

export default UploadMsg
